package com.example.alilist.activity;

import java.util.List;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.alilist.R;
import com.example.alilist.model.CellphoneItem;
import com.example.alilist.presenter.CellphonePresenter;
import com.example.alilist.view.CellphoneAdapter;
import com.example.alilist.view.ICellphoneListView;
import com.example.alilist.view.LettersBar;
import com.example.alilist.view.LettersBar.OnLetterChangedListener;

public class MainActivity extends Activity implements ICellphoneListView {

    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;

    private LinearLayout mHomeTopTitleLayout;
    private TextView mHomeTopTitle;
    private ListView mListView;
    private LettersBar mLettersBar;
    private TextView mLetterView;
    private CellphoneAdapter mCellphoneAdapter;

    private int mLastFirstVisibleItem = -1;
    private CellphonePresenter mCellphonePresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();

        mCellphonePresenter = new CellphonePresenter(this);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[] { Manifest.permission.READ_CONTACTS },
                    PERMISSIONS_REQUEST_READ_CONTACTS);
        } else {
            mCellphonePresenter.readCellphone(getApplicationContext());
        }

    }

    private void initViews() {
        mHomeTopTitleLayout = (LinearLayout) findViewById(R.id.home_top_title_layout);
        mHomeTopTitle = (TextView) findViewById(R.id.home_top_title);
        mLettersBar = (LettersBar) findViewById(R.id.home_letters_bar);
        mLetterView = (TextView) findViewById(R.id.home_letter_view);
        mLettersBar.setTextView(mLetterView);

        mLettersBar.setOnLetterChangedListener(new OnLetterChangedListener() {

            @Override
            public void onLetterChanged(String letter) {
                if (mCellphoneAdapter == null) {
                    return;
                }
                int position = mCellphoneAdapter.getPositionForSection(letter
                        .charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                }

            }
        });

        mListView = (ListView) findViewById(R.id.home_list_view);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(
                        getApplication(),
                        ((CellphoneItem) mCellphoneAdapter.getItem(position))
                                .getName()
                                + ":"
                                + ((CellphoneItem) mCellphoneAdapter
                                        .getItem(position)).getTel(),
                        Toast.LENGTH_SHORT).show();
            }
        });
        mListView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                if (totalItemCount <= 0) {
                    mHomeTopTitleLayout.setVisibility(View.INVISIBLE);
                    return;
                }
                mHomeTopTitleLayout.setVisibility(View.VISIBLE);
                CellphoneItem modelFirst = (CellphoneItem) mCellphoneAdapter
                        .getItem(firstVisibleItem);

                if (firstVisibleItem != mLastFirstVisibleItem) {
                    MarginLayoutParams params = (MarginLayoutParams) mHomeTopTitleLayout
                            .getLayoutParams();
                    params.topMargin = 0;
                    mHomeTopTitleLayout.setLayoutParams(params);
                    if (modelFirst.getSortLetters() != null) {
                        mHomeTopTitle.setText(modelFirst.getSortLetters());
                    }
                }
                int sectionFirst = mCellphoneAdapter
                        .getSectionForPosition(firstVisibleItem);
                int sectionSecond = mCellphoneAdapter
                        .getSectionForPosition(firstVisibleItem + 1);
                int positionFirst = mCellphoneAdapter
                        .getPositionForSection(sectionFirst);
                int positionSecond = mCellphoneAdapter
                        .getPositionForSection(sectionSecond);
                if (positionFirst != firstVisibleItem
                        && positionSecond == firstVisibleItem - 1) {
                    View childView = view.getChildAt(1);
                    if (childView != null) {
                        int titleHeight = mHomeTopTitleLayout.getHeight();
                        int top = childView.getTop();
                        MarginLayoutParams params = (MarginLayoutParams) mHomeTopTitleLayout
                                .getLayoutParams();
                        if (top <= titleHeight) {
                            params.topMargin = -(titleHeight - top);
                            mHomeTopTitleLayout.setLayoutParams(params);
                        }
                    }
                }
                mLastFirstVisibleItem = firstVisibleItem;
            }
        });
    }

    @Override
    public void onLoadedList(List<CellphoneItem> loadedDatas) {
        // TODO Auto-generated method stub
        if (loadedDatas == null || loadedDatas.size() == 0) {
            if (mHomeTopTitleLayout != null) {
                mHomeTopTitleLayout.setVisibility(View.INVISIBLE);
            }
            Toast.makeText(MainActivity.this, "You has no contact!",
                    Toast.LENGTH_LONG).show();
            return;
        }
        mCellphoneAdapter = new CellphoneAdapter(this, loadedDatas);
        mListView.setAdapter(mCellphoneAdapter);
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode,
            String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "READ_CONTACTS now",
                        Toast.LENGTH_SHORT).show();
                mCellphonePresenter.readCellphone(getApplicationContext());
            } else {
                // Permission Denied
                Toast.makeText(MainActivity.this,
                        "READ_CONTACTS Permission Denied", Toast.LENGTH_SHORT)
                        .show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
